from datetime import date, time, timedelta
from pprint import pprint
from django.http import HttpResponseRedirect
from exams.models import *
from django.shortcuts import render_to_response, redirect, HttpResponse, RequestContext, get_object_or_404
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required

def logout_view(request):
    logout(request)
    return HttpResponseRedirect('/')

@login_required
def home(request):

    return render_to_response("index.html", RequestContext(request))

# gets exams by date for one year period
@login_required
def studentIndex(request):

    #examTaken = ExamFinished.objects.all().filter(studentId = request.user.id, examEndDay__lt = date.today)

    examExpired = Exam.objects.all().filter(examEndDay__lt = date.today)#Expired exams
    examByToday = Exam.objects.all().filter(examStartDay__lt = date.today, examEndDay__gte = date.today)
    examFuture = Exam.objects.all().filter(examStartDay__gt = date.today)

    obj = { "examByToday":examByToday, "examExpired": examExpired, "examFuture": examFuture }
    return render_to_response("exams/_studentIndex.html",obj, RequestContext(request))

@login_required
def teacherIndex(request):

    if is_teacher(request.user) == False:
        message = "You don't have permission from the Universe and beyond to create an exam!"
        obj = {"message": message}
        return render_to_response('index.html',obj, RequestContext(request))
    else:
        teachersExam = Exam.objects.filter(owner__exact=request.user, active = 1)
        obj = {"teachersExam":teachersExam}
        return render_to_response("exams/_teacherIndex.html",obj, RequestContext(request))

#delete action for user
@login_required
def disableExam(request):
    if request.method == 'POST':
        disableExam = Exam.objects.get(id__exact= request.POST ['delete']) #pk id, if pk exists then SELECT does update
        disableExam.active -= 1
        disableExam.save()

        return render_to_response("exams/_teacherIndex.html", RequestContext(request))

#gets exam by request from student takeExam.html
@login_required
def takeExam(request, eId):
    if request.method == 'GET':
        exam = Exam.objects.get(id__exact=eId)
        questions = Question.objects.all().filter(examId__exact=eId)
        allAnswers = []

        for i in range(0,questions.count()):
            qid = questions[i].id
            qname = questions[i].name
            qanswers = Answer.objects.all().filter(questionId__exact=questions[i].id)
            allAnswers.append( {"qid": qid, "qname": qname, "qanswers": qanswers,} )

        obj = {"exam":exam, "allAnswers":allAnswers}
        return render_to_response("exams/takeExam.html",obj, RequestContext(request))

#Handlers the answers from students answerExam.html POST -!!!!takeExam

def answerExam(request):

    request.method == 'POST'
    #questions = Question.objects.all().filter(examId__exact= request.POST['examid'])

    #for i in range(0,questions.count()):
    #    new_examAnswers = StudentExams(
    #        studentId = request.user.id,
    #        examId = request.POST['examid'],
    #        questionId = request.POST ['question_'+str(questions[i].id)],
    #        answerId = request.POST ['answer_'+str(questions[i].id)])
    #    new_examAnswers.save()

    q_counter = 1
    whileBoolQ = True
    while whileBoolQ:
        if 'radio_'+str(q_counter) in request.POST:
            new_examAnswers = StudentExams(
                studentId = request.user.id,
                examId = request.POST['examid'],
                questionId = request.POST ['question'+str(q_counter)],
                answerValue = request.POST ['radio_'+str(q_counter)]
            )
            new_examAnswers.save()
            q_counter += 1
        else:
            whileBoolQ = False

    return HttpResponseRedirect('/')

#Creates new exam by teacher createExam.html
@login_required
def createExam(request):
    if request.method == 'GET':

        if is_teacher(request.user) == False:
            message = "You don't have permission from the Universe and beyond to create an exam!"
            obj = {"message": message}
            return render_to_response('index.html',obj, RequestContext(request))
        else:
            return render_to_response('exams/createExam.html', RequestContext(request))

    else:#Post
        request.method == 'POST'

        q_counter = 1
        q = []
        whileBoolQ = True
        while whileBoolQ:
            if 'question'+str(q_counter) in request.POST:
                q_name = request.POST ['question'+str(q_counter)]
                q_order = q_counter
                q_correctAnswer = request.POST ['rightAnswer_q'+str(q_counter)]

                a_counter = 1
                a = []
                whileBoolA = True
                while whileBoolA:
                    if 'q'+str(q_counter)+'_answer'+str(a_counter) in request.POST:
                        a_name = request.POST ['q'+str(q_counter)+'_answer'+str(a_counter)]
                        trueOrFalse = request.POST ['rightAnswer_q'+str(q_counter)]
                        a_order = a_counter
                        a.append({ "a_name": a_name, "trueOrFalse": trueOrFalse, "a_order": a_order })
                        a_counter += 1
                    else:
                        whileBoolA = False

                q.append({ "q_name": q_name, "q_order": q_order ,"q_correctAnswer": q_correctAnswer,"answers": a, "a_count": a_counter,})
                q_counter += 1

            else:
                whileBoolQ = False

        questCounter = 0
        for question in q:
            questCounter += 1

        new_exam = Exam(
            name = request.POST ['examName'],
            owner = request.user,
            # created = request.POST ['created'],
            examStartDay = request.POST ['examStart'],
            examEndDay = request.POST ['examEnd'],
            examStartTime = request.POST ['timeStart'],
            examEndTime = request.POST ['timeEnd'],
            averageGrade = 5,
            duration = 1,
        )
        new_exam.save()

        questionValue = 100/questCounter

        for questions in q:
            new_question = Question(
                name = questions["q_name"],
                order = questions["q_order"],
                value = questionValue,
                correctAnswer = questions["q_correctAnswer"],
                examId = Exam.objects.order_by('-pk')[0]
            )
            new_question.save()
            for answers in questions["answers"]:
                new_answer = Answer(
                    name = answers["a_name"],
                    order = answers["a_order"],
                    rightAnswer = answers["trueOrFalse"],
                    questionId = Question.objects.order_by('-pk')[0]
                )
                new_answer.save()

        return HttpResponseRedirect('/')


#Connected to a view that sums up the coorect aswers resultByStudent

def resultByStudent(request):
    if request.method == 'GET':
        allResultByStudent = ResultByStudent.objects.all().filter(studentId__exact = request.user.id)
        if allResultByStudent:
            obj = null
            for i in allResultByStudent:
                exam_counter = 0
                sum_grade = 0
                sum_grade += i.grade
                exam_counter +=1

                avg_grade = sum_grade/exam_counter

                obj  = {"allResultByStudent":allResultByStudent,"avg_grade":avg_grade}

            return render_to_response('exams/resultByStudent.html',obj, RequestContext(request))
        else:
            message = "You have not taken any exams, therefore we can not show you your grades"
            obj = {"message": message}
            return render_to_response("index.html",obj, RequestContext(request))

def is_teacher(user):

    return Teacher.objects.all().filter(username=user).count() > 0